<template>
    <div class="user-role-group">
        <div class="operation-bar">
            <el-input v-model="selectedRoleGroup.roleGroupName" placeholder="请输入角色组名称"
                style="width: 200px; margin-right: 10px" clearable @clear="handleSearch" @keyup.enter="handleSearch">
                <template #prefix>
                    <el-icon>
                        <Search />
                    </el-icon>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">新增角色组</el-button>
        </div>

        <el-table :data="roleGroups" style="width: 100%" @row-click="handleRowClick" v-loading="loading" height="calc(100vh - 250px)">
            <el-table-column type="index" label="序号" width="80">
                <template #default="scope">
                    {{ scope.$index + 1 + (currentPage - 1) * pageSize }}
                </template>
            </el-table-column>
            <el-table-column prop="roleGroupName" label="角色组名称" />
            <el-table-column prop="state" label="状态">
                <template #default="scope">
                    <el-tag v-if="scope.row.state == 1" type="success">启用</el-tag>
                    <el-tag v-else type="danger">禁用</el-tag>
                </template>

            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
                <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="最后修改时间">
                <template #default="scope">
                    {{ formatDate(scope.row.updateTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="primary" size="small" @click.stop="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 用户详情抽屉 -->
        <el-drawer v-model="drawerVisible" title="角色组用户列表" size="50%" :destroy-on-close="true">
            <div class="drawer-operation-bar">
                <el-input v-model="searchUser.username" placeholder="请输入用户名" style="width: 200px; margin-right: 10px" clearable @clear="handleUserSearch" @keyup.enter="handleUserSearch">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
                <el-input v-model="searchUser.realname" placeholder="请输入姓名" style="width: 200px; margin-right: 10px" clearable @clear="handleUserSearch" @keyup.enter="handleUserSearch">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
                <el-button type="primary" @click="handleAddUser">添加用户</el-button>
            </div>
            <el-table :data="userList" v-loading="userLoading" height="calc(100vh - 180px)">
                <el-table-column type="index" label="序号" width="80">
                    <template #default="scope">
                        {{ scope.$index + 1 + (currentPage - 1) * pageSize }}
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="realname" label="姓名" />
                <el-table-column prop="createTime" label="加入考勤组时间">
                    <template #default="scope">
                        {{ formatDate(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="最后修改时间">
                    <template #default="scope">
                        {{ formatDate(scope.row.modifyTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button type="danger" size="small" @click="handleRemoveUser(scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>

        <!-- 新增/编辑角色组对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增角色组' : '编辑角色组'" width="30%">
            <el-form :model="form" label-width="100px">
                <!-- <el-form-item label="角色组ID" v-if="dialogType === 'edit'">
                    <el-input v-model="form.roleGroupId" placeholder="请输入角色组ID" disabled/>
                </el-form-item> -->
                <el-form-item label="角色组名称">
                    <el-input v-model="form.roleGroupName" placeholder="请输入角色组名称" />
                </el-form-item>
                <el-form-item label="状态" v-if="dialogType === 'edit'">
                    <el-radio-group v-model="form.state">
                        <el-radio :value="1">启用</el-radio>
                        <el-radio :value="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 新增用户对话框 -->
        <el-dialog v-model="userDialogVisible" title="添加用户" width="30%">
            <el-form :model="userForm" label-width="100px">
                <el-form-item label="用户名">
                    <el-select v-model="userForm.usernames" placeholder="请选择用户" style="width: 100%" filterable multiple collapse-tags collapse-tags-tooltip>
                        <el-option v-for="item in userOptions" :key="item.username" :label="item.realname" :value="item.username">
                            <span>{{ item.realname }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.username }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="userDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitUserForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import dayjs from 'dayjs'
import { Search } from '@element-plus/icons-vue'

export default {
    name: 'UserRoleGroup',
    components: {
        Search
    },
    data() {
        return {
            roleGroups: [],
            userList: [],
            userOptions: [],
            loading: false,
            userLoading: false,
            drawerVisible: false,
            dialogVisible: false,
            userDialogVisible: false,
            dialogType: 'add',
            selectedRoleGroup: {
                roleGroupName: '',
            },
            searchUser: {
                username: '',
                realname: '',
            },
            userForm: {
                usernames: [],
                roleGroupId: null
            },
            form: {
                roleGroupName: '',
                state: 1
            },
            currentPage: 1,
            pageSize: 10,
            total: 0
        }
    },
    methods: {
        async getRoleGroups() {
            this.loading = true

            // TODO: 替换为实际的API调用
            this.$post('/findByRoleGroup', {
                data: this.selectedRoleGroup,
                pageNum: this.currentPage,
                pageSize: this.pageSize
            }).then(res => {
                if (res.code == 200) {
                    this.roleGroups = res.data
                    this.total = res.total
                } else {
                    this.$message.error(res.msg)
                }
            }).catch(err => {
                //   this.$message.error('获取角色组列表失败')
                console.log(err)
            }).finally(() => {
                this.loading = false
            })

        },
        async getUserList(roleGroupId) {
            this.userLoading = true
            this.searchUser.roleGroupId = roleGroupId
            this.userList = []
            this.$get('/findOneUserRoleGroupDetails', {
                roleGroupId: roleGroupId,
                username: this.searchUser.username,
                realname: this.searchUser.realname
            }).then(res => {
                if (res.code == 200) {
                    this.userList = res.data.userList
                } else {
                    this.$message.error(res.msg)
                }
            }).catch(err => {
                console.log(err)
            }).finally(() => {
                this.userLoading = false
            })
        },
        handleRowClick(row) {
            this.drawerVisible = true
            this.getUserList(row.roleGroupId)
        },
        handleDelete(row) {
            this.$msgbox.confirm(
                '确定要删除该角色组吗？',
                '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                this.$get('/deleteRoleGroup', { 
                    roleGroupId: row.roleGroupId
                }).then(res => {
                    if (res.code == 200) {
                        this.$message.success('删除成功')
                        this.getRoleGroups()
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }).catch(err => {
                console.log(err)
            })
        },
        handleEdit(row) {
            this.dialogType = 'edit'
            this.form = {
                roleGroupId: row.roleGroupId,
                roleGroupName: row.roleGroupName,
                state: row.state
            }

            this.dialogVisible = true
        },
        handleAdd() {
            this.dialogType = 'add'
            this.form = {
                roleGroupName: '',
            }
            
            this.dialogVisible = true
        },
        submitForm() {
  
            if (this.dialogType === 'add') {
                if (this.form.roleGroupName == '' || this.form.roleGroupName == null) {
                    this.$message.error('请输入角色组名称')
                    return
                }
                // 新增角色组
                this.$post('/saveRoleGroup', this.form).then(res => {
                    if (res.code == 200) {
                        this.$message.success('添加成功')
                        this.dialogVisible = false
                        this.getRoleGroups()
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    console.log(err)
                })
            } else {
                if (this.form.roleGroupName == '' || this.form.roleGroupName == null) {
                    this.$message.error('请输入角色组名称')
                    return
                }
                if (this.form.state == undefined || this.form.state == null) {
                    this.$message.error('请选择状态')
                    return
                }
                if (this.form.roleGroupId == undefined || this.form.roleGroupId == null) {
                    this.$message.error('请输入角色组ID')
                    return
                }
                // 更新角色组状态
                this.$post('/updateRoleGroupState', this.form).then(res => {
                    if (res.code == 200) {
                        this.$message.success('更新成功')
                        this.dialogVisible = false
                        this.getRoleGroups()
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }
        },
        handleSearch() {
            this.currentPage = 1
            this.getRoleGroups()
        },
        formatDate(date) {
            return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
        },
        // 处理每页显示数量变化
        handleSizeChange(val) {
            this.pageSize = val
            this.currentPage = 1
            this.getRoleGroups()
        },
        // 处理页码变化
        handleCurrentChange(val) {
            this.currentPage = val
            this.getRoleGroups()
        },
        handleUserSearch() {
            this.getUserList(this.searchUser.roleGroupId)
        },
        handleAddUser() {
            this.userForm = {
                usernames: [],
                roleGroupId: this.searchUser.roleGroupId
            }
            this.getUserOptions()
            this.userDialogVisible = true
        },
        handleRemoveUser(row) {
            this.$msgbox.confirm(
                '确定要移除该用户吗？',
                '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                this.$get('/deleteUserRoleGroup', {
                    id: row.id
                }).then(res => {
                    if (res.code == 200) {
                        this.$message.success('移除成功')
                        this.getUserList(this.searchUser.roleGroupId)
                    } else {
                        this.$message.error(res.msg)
                    }
                }).catch(err => {
                    console.log(err)
                })
            }).catch((err) => {
                this.$message.error('移除失败')
                console.log(err)
            })
        },
        submitUserForm() {
            if (!this.userForm.usernames || this.userForm.usernames.length === 0) {
                this.$message.error('请选择用户')
                return
            }
            console.log(this.userForm);
            
            this.$post('/saveUserRoleGroup', {
                roleGroupId: this.userForm.roleGroupId,
                usernames: this.userForm.usernames
            }).then(res => {
                if (res.code == 200) {
                    this.$message.success('添加成功!')
                    if (res.data != null && res.data != '') {
                        alert('日志为：' + res.data)
                    }
                    this.userDialogVisible = false
                    this.getUserList(this.searchUser.roleGroupId)
                } else {
                    this.$message.error(res.msg)
                }
            }).catch(err => {
                console.log(err)
            })
        },
        getUserOptions() {//获取用户列表
            this.$get('/findAllNoRoleGroup',{
                roleGroupId: this.searchUser.roleGroupId
            }).then(res => {
                if (res.code == 200) {
                    this.userOptions = res.data
                } else {
                    this.$message.error(res.msg)
                }
            }).catch(err => {
                console.log(err)
            })
        }
    },
    mounted() {
        this.getRoleGroups()
    }
}
</script>

<style scoped>
.user-role-group {
    padding: 20px;
}

.operation-bar {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.drawer-operation-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
    gap: 10px;
}
</style>
